#!/usr/bin/python
# coding=utf8
#
# Copyright (C) 2011 XNData contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


__author__ = "zhangchitc@gmail.com"

import urllib2, urllib
import re

class LoginUrlMgr:

    @staticmethod
    def login_url ():
        return "http://passport.renren.com/PLogin.do?domain=renren.com"



class LoginPageFetcher:

    @staticmethod
    def fetch_login_page (opener, uname, upass):
        # Setup request object constitued login url and post data
        request = urllib2.Request (LoginUrlMgr.login_url ())
        data = {'email'     : uname,
                'password'  : upass,
                'submit'    : '登录'}
        request.add_data (urllib.urlencode(data))

        return opener.open (request).read ()



class LoginPageParser:
    
    @staticmethod
    def parse_login_page (html):
        m = re.compile (r'XN\.user\.id = \'(?P<userid>.*)\';').search (html)
        user_id = m.group ('userid')

        m = re.compile (r'XN\.user\.name = "(?P<username>.*)";').search (html)
        user_name = m.group ('username')
        user_name = urllib.unquote (user_name)

        return {"login_state"   : user_id != "",
                "user_id"       : user_id, 
                "user_name"     : user_name}

